import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

// const DEFAULT_AVATAR = require('@/assets/img/z.jpg')

// 修改状态初始化方式
const state = {
  token: null, // 初始化为null，避免立即调用getToken()
  name: '',
  avatar: localStorage.getItem('user_avatar') || '' // DEFAULT_AVATAR, // 优先从本地存储加载
  // roles: [],
  // permissions: []
}

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, {
      token: null,
      name: '',
      avatar: localStorage.getItem('user_avatar') || '' // DEFAULT_AVATAR, // 优先从本地存储加载
      // roles: [],
      // permissions: []
    })
    localStorage.removeItem('user_avatar')
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    // 永久存储逻辑（关键修改）
    const validAvatar = avatar || state.avatar || ''
    state.avatar = validAvatar
    localStorage.setItem('user_avatar', validAvatar)
    sessionStorage.setItem('current_avatar', validAvatar) // 会话级备份
  },
  // SET_ROLES: (state, roles) => {
  //   state.roles = roles
  // },
  // SET_PERMISSIONS: (state, permissions) => {
  //   state.permissions = permissions
  // },
  // ======================[新增开始]======================
  SET_INFO: (state, info) => {
    if (!info) return // 新增：防御性判断

    state.name = info.name || ''
    // 修改这里：优先保留现有头像，只有当 info.avatar 有值且当前无头像时才更新
    // 仅当接口返回新头像时才更新（重要！）
    if (info.avatar) state.avatar = info.avatar
    state.roles = info.roles || state.roles
    state.permissions = info.permissions || state.permissions

    // 新增token更新逻辑（但不持久化）
    if (info.token) state.token = info.token

    // // 开发环境调试
    // if (process.env.NODE_ENV === 'development') {
    //   console.log('[用户信息更新]', cloneDeep(info));
    // }
  }
}

const actions = {
  // 初始化token和用户基本信息
  initAuth ({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      const token = getToken()
      if (token) {
        commit('SET_TOKEN', token)
        // 尝试获取用户信息
        dispatch('getInfo')
          .then(() => resolve())
          .catch(() => {
            // 获取用户信息失败时只保留token
            resolve()
          })
      } else {
        resolve()
      }
    })
  },

  /**
   * 设置用户信息（整合多个mutation调用）
   * @param {Object} userInfo - 包含用户信息的对象
   */
  setUserInfo ({ commit }, userInfo) {
    if (!userInfo) {
      console.error('setUserInfo: 参数不能为空')
      return
    }

    commit('SET_INFO', userInfo)
    // 如果传入token则单独更新（兼容不同场景）
    if (userInfo.token) {
      commit('SET_TOKEN', userInfo.token)
      setToken(userInfo.token)
    }
  },

  // 用户登录
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      // 这里应该是调用真实API的地方
      login({
        username: userInfo.username.trim(),
        password: userInfo.password
      }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo ({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      if (!state.token) {
        return reject(new Error('未获取到有效token'))
      }

      getInfo(state.token)
        .then(response => {
          const { data } = response || {}
          if (!data?.roles?.length) {
            throw new Error('用户角色信息缺失')
          }

          commit('SET_NAME', data.name || '')

          // commit('SET_AVATAR', data.avatar || require('@/assets/img/z.jpg'))
          const avatarPath = data?.avatar
            ? (data.avatar.startsWith('http') ? data.avatar : require(`@/assets/${data.avatar}`))
            // : require('@/assets/img/z.jpg')
            : ''// 改为空字符串

          commit('SET_AVATAR', avatarPath) // 使用 SET_AVATAR 保证持久化

          commit('SET_ROLES', data.roles)
          commit('SET_PERMISSIONS', data.permissions || [])
          resolve(data)
        })
        .catch(error => {
          console.error('获取用户信息失败:', error)
          removeToken()

          // commit('SET_AVATAR', require('@/assets/img/z.jpg')) // 失败时设置默认头像

          commit('RESET_STATE')
          reject(error)
        })
    })
  },

  // 用户退出
  logout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 正式环境处理
      const logoutPromise = state.token ? logout(state.token) : Promise.resolve()

      logoutPromise
        .then(() => {
          // 清除所有用户状态
          removeToken()
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch(error => {
          console.error('退出异常:', error)
          // 即使API调用失败也执行清理
          removeToken()
          resetRouter()
          commit('RESET_STATE')
          resolve() // 仍然resolve以确保流程继续
        })
    })
  },

  // 移除token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  },

  // 上传头像
  async uploadAvatar ({ commit }, file) {
    return new Promise((resolve) => {
      // 1. 创建临时URL（即时显示）
      const tempUrl = URL.createObjectURL(file)
      commit('SET_AVATAR', tempUrl)

      // 2. 模拟上传延迟
      setTimeout(() => {
        // 3. 生成一个永久的base64 URL用于存储
        const reader = new FileReader()
        reader.onload = (e) => {
          const base64Url = e.target.result

          // 更新Vuex状态和本地存储
          commit('SET_AVATAR', base64Url)
          localStorage.setItem('user_avatar', base64Url)

          resolve(base64Url)
        }
        reader.readAsDataURL(file)
      }, 500)
    })
  }

}

const getters = {
  // 获取用户token
  token: state => state.token,
  // 获取用户名
  name: state => state.name,
  // 获取用户头像
  // 修改头像获取逻辑，永不返回默认头像
  avatar: state => state.avatar || localStorage.getItem('user_avatar'), // || this.defaultAvatar,
  // 获取用户角色
  // roles: state => state.roles,
  // 获取用户权限
  // permissions: state => state.permissions,
  // 默认头像
  defaultAvatar: () => require('@/assets/img/z.jpg'), // 新增默认头像getter
  safeAvatar: (state, getters) => {
    return state.avatar || getters.defaultAvatar
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
